export const objToBase64 = (obj) => {
  const jsonStr = JSON.stringify(obj);
  // Use browser's btoa() function for base64 encoding
  return btoa(unescape(encodeURIComponent(jsonStr)));
};

export const base64ToObj = (base64) => {
  // Use browser's atob() function for base64 decoding
  const decodedString = decodeURIComponent(escape(atob(base64)));
  return JSON.parse(decodedString);
};

/**
 * 解析Base64编码的二维码图像内容
 * @param base64String Base64编码的二维码图像字符串 (可能带有 data:image/*;base64, 前缀)
 * @returns 解析出的二维码内容
 */
export const decodeQrCodeFromBase64 = async (base64String: string): Promise<string | null> => {
  return new Promise((resolve) => {
    // 处理可能包含前缀的Base64字符串
    let imageDataString = base64String;
    if (base64String.startsWith('data:image')) {
      // 如果有data:image前缀，提取实际的Base64数据部分
      const parts = base64String.split(',');
      if (parts.length === 2) {
        imageDataString = parts[1];
      }
    }

    // 构造完整的Base64数据URL
    const dataUrl = `data:image/png;base64,${imageDataString}`;

    const img = new window.Image();
    img.crossOrigin = "anonymous";

    img.onload = () => {
      const canvas = document.createElement('canvas');
      canvas.width = img.width;
      canvas.height = img.height;
      const ctx = canvas.getContext('2d');

      ctx?.drawImage(img, 0, 0);
      const imageData = ctx?.getImageData(0, 0, img.width, img.height);

      if (imageData) {
        // 动态导入jsQR库来解析二维码
        import('jsqr').then((jsQR) => {
          const code = jsQR.default(imageData.data, imageData.width, imageData.height);
          resolve(code?.data || null);
        }).catch(() => {
          resolve(null);
        });
      } else {
        resolve(null);
      }
    };

    img.onerror = () => {
      console.error("图片加载失败");
      resolve(null);
    };

    img.src = dataUrl;
  });
};


/**
 * 解码URL参数并返回解析后的对象
 * @param {string} encodedUrl 被编码的URL
 * @returns {Object} 解析后的参数对象
 */
export const decodeUrlParams = (encodedUrl: any): any => {
  try {
    // 1. 提取URL中的查询参数部分
    const url = new URL(decodeURIComponent(encodedUrl));
    const hash = url.hash.replace(/^#\/?/, ''); // 去掉"#/"前缀

    // 2. 从hash部分提取参数
    const params = {};
    const hashParts = hash.split('?');
    if (hashParts.length > 1) {
      const queryString = hashParts[1];
      const keyValuePairs = queryString.split('&');

      // 3. 解析每个键值对
      keyValuePairs.forEach(pair => {
        const [key, value] = pair.split('=');
        params[key] = decodeURIComponent(value || '');

        // 4. 处理可能存在的JSON参数(如codeParam)
        if (params[key].startsWith('{') && params[key].endsWith('}')) {
          try {
            params[key] = JSON.parse(params[key]);
          } catch (e) {
            console.warn(`Failed to parse JSON parameter "${key}"`, e);
          }
        }
      });
    }

    return params;
  } catch (error) {
    console.error('URL解析错误:', error);
  }
}
